package com.itita.ww2.game.lottery;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.itita.ww2.core.WW2Exception;
import com.itita.ww2.data.LotteryConfig;
import com.itita.ww2.data.LotteryConfig.LotteryItem;
import com.itita.ww2.enums.WW2ExceptionCode;
import com.itita.ww2.game.user.UserRewardDispatch.RewardType;
import com.itita.ww2.model.user.UserProfile;
import com.itita.ww2.utils.random.RandomSelector;
import com.smartfoxserver.v2.entities.data.ISFSObject;

/**
 * 抽奖
 * @author NorthLan
 *
 */
public class LotteryService {
	private static Lock lock = new ReentrantLock();

	public static List<Integer> lottery(UserProfile userProfile, int times) throws WW2Exception {
		// 用户资源判定
		int userLv = userProfile.getUserInfo().getLevel();
		ISFSObject resObj = LotteryConfig.getLotteryResourceByLv(times, userLv);
		if (!userProfile.getResManager().isResEnoughMulti(resObj)) {
			throw new WW2Exception(WW2ExceptionCode.USER_RES_NOT_ENOUGH);
		}

		List<LotteryItem> items = new ArrayList<>();
		lock.lock();
		try {
			RandomSelector<LotteryItem, Number> selector = new RandomSelector<>(
					LotteryConfig.getLotteryJackpot(userLv));
			items = selector.randomMultiTimesAsList(times);
		} finally {
			lock.unlock();
		}

		// 扣除资源
		userProfile.getResManager().operResWithMaxCheck(resObj, false);

		ISFSObject lotteryItems = LotteryItem.convert2SFSObject(items);

		userProfile.getRewardManager().onReward(RewardType.LOTTERY, lotteryItems);

		return LotteryItem.convert2SFSArray(items);
	}
}
